package com.xiaoxie.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 自定义路由断言工厂
 * 自定义配置会员等级，userType,按钻/金/银和yml配置的会员等级，适配是否可以访问
 */
@Component
public class MyRoutePredicateFactory  extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {

    // 空参构造方法，内部调用super
    public MyRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                if(userType == null) return false;
                if(userType.equals(config.getUserType())) {
                    return true;
                }
                return false;
            }
        };
    }

    // 支持短格式配置，即配置userType
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }

    // Config类就是路由断言规则
    @Validated
    public static class Config {
        @Setter
        @Getter
        @NotEmpty
        private String userType;
    }
}
